// 由生产者驱动多个消费者

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>

#include "../include/thread.h"
#include "../include/mutex.h"
#include "../include/condvar.h"

using namespace mix;

std::string buffer;
Mutex bufferLock;
CondVar cond( bufferLock);

void thread1_run() {
    for ( int i = 0; i < 10;) {

        bufferLock.lock();
        if ( buffer.empty()) {
            buffer = "car.";
            printf( "product a %s\n", buffer.c_str());
            bufferLock.unlock();
            cond.signalAll();
            ++i;
        }
        else  
            bufferLock.unlock();

        Thread::sleep( rand() % 500);
    }
}


void thread2_run() {
    for ( int i = 0; i < 10; ++i) {

        bufferLock.lock();
        if ( buffer.empty())
            cond.wait( 1000);
        if ( !buffer.empty()) {
            printf( "2 buy a %s\n", buffer.c_str());
            buffer.clear();
        }
        bufferLock.unlock();
        Thread::yield();
    }

}

void thread3_run() {
    for ( int i = 0; i < 10; ++i) {

        bufferLock.lock();
        if ( buffer.empty())
            cond.wait( 1000);
        if ( !buffer.empty()) {
            printf( "3 buy a %s\n", buffer.c_str());
            buffer.clear();
        }
        bufferLock.unlock();
        Thread::yield();
    }

}


int main() {
    Thread t1( thread1_run);
    Thread t2( thread2_run);
    Thread t3( thread3_run);

    t1.start();
    t2.start();
    t3.start();

    t1.join();
    t2.join();
    t3.join();

    return 0;
}
